package cn.com.dycc.common.http;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.dycc.util.StringUtil;

public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper{

	private final byte[] body;
	
	
	public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
		body=HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));	
	}

	
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	
	public ServletInputStream getInputStream() throws IOException {
		System.out.println("创建新流++++++++++++++++++++:"+new String(body,Charset.forName("UTF-8")));
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> map=mapper.readValue(body, Map.class);
		Set<String> keys=map.keySet();
		for(String key:keys){
			if(map.get(key) instanceof String){
				map.put(key, StringUtil.filterContent((String)map.get(key)));
			}
			
		}
		String new_map=mapper.writeValueAsString(map);
		System.out.println("new_map:"+new_map);
		
		final ByteArrayInputStream bais=new ByteArrayInputStream(new_map.getBytes(Charset.forName("UTF-8")));
		return new ServletInputStream() {
		
			public int read() throws IOException {
				return bais.read();
			}

			@Override
			public boolean isFinished() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isReady() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void setReadListener(ReadListener arg0) {
				// TODO Auto-generated method stub
				
			}
		};
	}


	
	public String getHeader(String name) {
		return super.getHeader(name);
	}


	
	public Enumeration<String> getHeaderNames() {
		return super.getHeaderNames();
	}

	
	public Enumeration<String> getHeaders(String name) {
		return super.getHeaders(name);
	}


	
	public String getParameter(String name) {
		System.out.println("执行获取参数值");
		return StringUtil.filterContent(super.getParameter(name));
	}
	
	

	

	
	
	

}
